package DigitalNetwork;

import java.awt.Dimension;
import java.awt.Graphics;
import java.util.*;
import java.util.ArrayList;
import javax.swing.JPanel;

public class NetworkView extends JPanel implements ISimulatorListener {

	private List<UnitView> units;
	private List<Dimension> wires;
	public static final int UNIT_SIZE = 60;

	/** [Konstruktor]
	 * Letrehozza a Unit-listat
	 *
	 */
	public NetworkView() {
		this.units = new ArrayList<UnitView>();
		this.wires = new ArrayList<Dimension>();
	}

	/**
	 * 
	 */
	public void reset() {
		this.units = new ArrayList<UnitView>();
		this.wires = new ArrayList<Dimension>();
	}

	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.translate(5, 15);
		//Drotok kirajzolasa
		ListIterator<Dimension> iD = this.wires.listIterator();
		while (iD.hasNext()) {
			Dimension d0 = iD.next();
			if (iD.hasNext()) {
				Dimension d1 = iD.next();
				g.drawLine(d0.width, d0.height, d1.width, d1.height);
			} else {
				// Paratlan pontok.
			}
		}
		//Elemek krajzolasa.
		ListIterator<UnitView> iU = this.units.listIterator();
		while (iU.hasNext()) {
			UnitView uv = iU.next();
			g.translate(uv.unit.coordinates.get(0), uv.unit.coordinates.get(1));
			uv.draw(g);
			g.translate(-uv.unit.coordinates.get(0), -uv.unit.coordinates.get(1));
		}
	}

	/**
	 *
	 * @return
	 */
	public void onIteration() {
		System.out.println("NetworkVeiw - onIteration");
	}

	/**
	 * Unit hozzaadasakor letrehoz egy hozza tartozo view-t
	 * @param u Az elem, amelyhez a view-t letre kell hozni.
	 */
	public void onUnitAdded(Unit u) {
		String type = u.getType();
		if (type.equals("Button")) {
			this.units.add(new ButtonView(u));
		} else if (type.equals("Generator")) {
			this.units.add(new GeneratorView(u));
		} else if (type.equals("LED")) {
			this.units.add(new LEDView(u));
		} else if (type.equals("Oscilloscope")) {
			this.units.add(new OscilloscopeView(u));
		} else if (u.getCategory().equals("Gate")) {
			this.units.add(new GateView(u));
		} else {
			// Nem okes.
			this.units.add(new UnitView(u));
		}
	}

	/**
	 *
	 * @param u1
	 * @param x
	 * @param u2
	 * @param y
	 */
	public void onConnection(Unit u1, int x, Unit u2, int y) {
		int ux = UNIT_SIZE / u1.outputs.size();
		int uy = UNIT_SIZE / u2.inputs.size();
		wires.add(new Dimension(
			u1.coordinates.get(0) + UNIT_SIZE,
			u1.coordinates.get(1) + ux * x + ux / 2));
		wires.add(new Dimension(
			u2.coordinates.get(0),
			u2.coordinates.get(1) + uy * y + uy / 2));
	}
}
